import _regeneratorRuntime from "@babel/runtime/regenerator";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isString from "lodash/isString";
import _isArray from "lodash/isArray";
import _isNil from "lodash/isNil";
import _omit from "lodash/omit";
import _isFunction from "lodash/isFunction";
import _isEmpty from "lodash/isEmpty";

var _dec, _dec2, _dec3, _dec4, _dec5, _class, _class2;

/**
 * 多选lov组件
 * @date: 2020-5-7
 */

/* eslint-disable react/no-did-update-set-state */

/* eslint-disable no-unused-expressions */
import React from 'react';
import { Modal, Input, Icon, message, Tag } from 'antd';
import { Bind } from 'lodash-decorators';
import uuid from 'uuid/v4';
import intl from "../../../../utils/intl";
import { getResponse } from "../../../../utils/utils";
import { queryLov, queryMapIdpValue } from "../../../../services/api";
import TransferModal from "./LovModal";
import ViewOnlyModal from "./ViewOnlyModal";
import "./index.less";
var TransferLov = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), (_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(TransferLov, _React$Component);

  var _super = _createSuper(TransferLov);

  // 选中记录
  function TransferLov(props) {
    var _this;

    _classCallCheck(this, TransferLov);

    _this = _super.call(this, props);
    _this.records = undefined;
    _this.state = void 0;
    _this.loading = false;
    _this.modalRef = {
      current: null
    };
    _this.state = {
      displayData: [],
      translateData: {},
      values: [],
      textField: props.textField,
      lov: {},
      loading: false,
      ldpData: {},
      modalVisible: false,
      saveLoading: false
    };
    _this.modalRef = React.createRef();
    return _this;
  }

  _createClass(TransferLov, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props = this.props,
          value = _this$props.value,
          displayData = _this$props.displayData,
          translateData = _this$props.translateData;
      this.initDisplayData(value, displayData, translateData);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var _this$props2 = this.props,
          displayData = _this$props2.displayData,
          value = _this$props2.value;
      var translateData = this.props.translateData;

      if (value !== prevProps.value || displayData !== prevProps.displayData) {
        this.initDisplayData(value, displayData, translateData);
      }
    }
  }, {
    key: "initDisplayData",
    value: function initDisplayData(value, displayData, translateData) {
      var values = [];
      var _this$props3 = this.props,
          showAll = _this$props3.showAll,
          viewOnly = _this$props3.viewOnly;

      if (_isString(value) && value !== '') {
        values = value.split(',');
      }

      if (viewOnly) {
        this.setState({
          values: values
        });
        return;
      }

      if (values.length > 0) {
        var newTranslateData = {};
        var newDisplayData = [];

        if (typeof translateData === 'string' && translateData !== '') {
          newTranslateData[values[0]] = translateData;
        } else {
          newTranslateData = _objectSpread({}, translateData);
        }

        newTranslateData = _objectSpread(_objectSpread({}, newTranslateData), this.state.translateData);

        if (_isArray(displayData) && _isEmpty(this.state.displayData)) {
          newDisplayData = displayData;
        }

        newDisplayData = (showAll ? values : values.slice(0, 5)).map(function (i, index) {
          return newTranslateData[i] || newDisplayData[index] || i;
        });

        if (values.length > 5 && !showAll) {
          newDisplayData.push('...');
        }

        this.setState({
          displayData: newDisplayData,
          translateData: newTranslateData,
          values: values
        });
      }
    }
  }, {
    key: "selectAndClose",
    value: function () {
      var _selectAndClose = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _this$props4, form, onChange, viewOnly, translateData, _yield$this$modalRef$, values, meaningMap, value, textField, displayData;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this$props4 = this.props, form = _this$props4.form, onChange = _this$props4.onChange, viewOnly = _this$props4.viewOnly;
                translateData = this.state.translateData;
                this.setState({
                  saveLoading: true
                });

                if (!viewOnly) {
                  _context.next = 6;
                  break;
                }

                this.setState({
                  saveLoading: false,
                  modalVisible: false
                });
                return _context.abrupt("return");

              case 6:
                _context.next = 8;
                return this.modalRef.current.getSelectedData();

              case 8:
                _yield$this$modalRef$ = _context.sent;
                values = _yield$this$modalRef$.values;
                meaningMap = _yield$this$modalRef$.meaningMap;
                value = values.length > 0 ? values.join(',') : undefined;
                textField = this.getTextField();

                if (!_isNil(textField)) {
                  form && form.setFieldsValue(_defineProperty({}, textField, value));
                }

                typeof onChange === 'function' && onChange(value);
                displayData = (values.length > 5 ? values.slice(0, 5) : values).map(function (i) {
                  return meaningMap[i];
                });

                if (values.length > 5) {
                  displayData.push('...');
                }

                this.setState({
                  saveLoading: false,
                  translateData: _objectSpread(_objectSpread({}, translateData), meaningMap),
                  displayData: displayData,
                  values: values,
                  modalVisible: false
                });

              case 18:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function selectAndClose() {
        return _selectAndClose.apply(this, arguments);
      }

      return selectAndClose;
    }()
  }, {
    key: "getTextField",
    value: function getTextField() {
      var form = this.props.form;
      var textField = this.state.textField;

      if (form && textField) {// form.registerField(textField);
      }

      return textField;
    }
  }, {
    key: "onCancel",
    value: function onCancel() {
      var _this$props$onCancel = this.props.onCancel,
          onCancel = _this$props$onCancel === void 0 ? function (e) {
        return e;
      } : _this$props$onCancel;
      this.setState({
        modalVisible: false
      });

      if (_isFunction(onCancel)) {
        onCancel();
      }
    }
  }, {
    key: "showLoading",
    value: function showLoading() {
      var partialState = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.setState(_objectSpread({
        loading: true
      }, partialState));
    }
  }, {
    key: "hideLoading",
    value: function hideLoading() {
      this.setState({
        loading: false
      });
    }
  }, {
    key: "onSearchBtnClick",
    value: function onSearchBtnClick() {
      var _this2 = this;

      var _this$props5 = this.props,
          _this$props5$disabled = _this$props5.disabled,
          disabled = _this$props5$disabled === void 0 ? false : _this$props5$disabled,
          _this$props5$onClick = _this$props5.onClick,
          onClick = _this$props5$onClick === void 0 ? function (e) {
        return e;
      } : _this$props5$onClick,
          _this$props5$lovOptio = _this$props5.lovOptions;
      _this$props5$lovOptio = _this$props5$lovOptio === void 0 ? {} : _this$props5$lovOptio;
      var customValueField = _this$props5$lovOptio.valueField,
          customDisplayField = _this$props5$lovOptio.displayField;
      if (disabled || this.loading) return; // 节流

      var _this$props6 = this.props,
          viewCode = _this$props6.code,
          tenantId = _this$props6.originTenantId;
      this.loading = true;
      this.showLoading({
        loading: true,
        modalVisible: true,
        lovModalKey: uuid()
      });
      queryLov({
        viewCode: viewCode,
        tenantId: tenantId
      }).then(function (oriLov) {
        var lov = _objectSpread({}, oriLov);

        if (customValueField) {
          lov.valueField = customValueField;
        }

        if (customDisplayField) {
          lov.displayField = customDisplayField;
        }

        if (!_isEmpty(lov)) {
          var hasCode = lov.viewCode,
              _lov$title = lov.title,
              title = _lov$title === void 0 ? '' : _lov$title; // 获取独立值集编码

          var valueList = lov.queryFields.filter(function (item) {
            return item.dataType === 'SELECT';
          });

          if (valueList.length > 0) {
            var valueCode = {};
            valueList.forEach(function (_ref) {
              var sourceCode = _ref.sourceCode;

              if (sourceCode) {
                valueCode[sourceCode] = sourceCode;
              }
            });
            queryMapIdpValue(valueCode).then(function (res) {
              if (getResponse(res, function () {})) {
                _this2.setState({
                  ldpData: res
                });
              }
            });
          }

          if (hasCode) {
            _this2.setState({
              lov: lov,
              title: title
            });

            if (_isFunction(onClick)) {
              onClick();
            }
          } else {
            _this2.hideLoading();

            message.error(intl.get('cpaas.common.components.lov.notification.undefined').d('值集视图未定义!'));
          }
        }
      }).finally(function () {
        _this2.hideLoading();

        _this2.loading = false;
      });
    }
  }, {
    key: "searchButton",
    value: function searchButton() {
      if (this.state.loading) {
        return /*#__PURE__*/React.createElement(Icon, {
          key: "search",
          type: "loading"
        });
      }

      return /*#__PURE__*/React.createElement(Icon, {
        key: "search",
        type: "search",
        onClick: this.onSearchBtnClick,
        style: {
          cursor: 'pointer',
          color: '#666'
        }
      });
    }
  }, {
    key: "emitEmpty",
    value: function emitEmpty() {
      var _this3 = this;

      var _this$props7 = this.props,
          form = _this$props7.form,
          _this$props7$onClear = _this$props7.onClear,
          onClear = _this$props7$onClear === void 0 ? function (e) {
        return e;
      } : _this$props7$onClear,
          value = _this$props7.value,
          onChange = _this$props7.onChange;

      if (onChange) {
        var records = {};
        this.setState({
          displayData: []
        }, function () {
          onChange(undefined, records);

          var textField = _this3.getTextField();

          if (form && textField) {
            form.setFieldsValue(_defineProperty({}, textField, undefined));
          }
        });
      }

      if (_isFunction(onClear)) {
        onClear(value);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this$state = this.state,
          stateDisplay = _this$state.displayData,
          _this$state$ldpData = _this$state.ldpData,
          ldpData = _this$state$ldpData === void 0 ? {} : _this$state$ldpData,
          values = _this$state.values,
          saveLoading = _this$state.saveLoading;
      var _this$props8 = this.props,
          value = _this$props8.value,
          queryParams = _this$props8.queryParams,
          queryInputProps = _this$props8.queryInputProps,
          style = _this$props8.style,
          className = _this$props8.className,
          isDbc2Sbc = _this$props8.isDbc2Sbc,
          _this$props8$delimma = _this$props8.delimma,
          delimma = _this$props8$delimma === void 0 ? '/' : _this$props8$delimma,
          _this$props8$displayD = _this$props8.displayData,
          displayData = _this$props8$displayD === void 0 ? [] : _this$props8$displayD,
          _this$props8$allowCle = _this$props8.allowClear,
          allowClear = _this$props8$allowCle === void 0 ? true : _this$props8$allowCle,
          viewOnly = _this$props8.viewOnly,
          code = _this$props8.code;
      var omitProps = ['onOk', 'onCancel', 'onClick', 'onClear', 'textField', 'lovOptions']; // eslint-disable-next-line no-nested-ternary

      var text = _isNil(value) ? '' : (stateDisplay.length > 0 ? stateDisplay : displayData).join(delimma);

      var inputStyle = _objectSpread(_objectSpread({}, style), {}, {
        verticalAlign: 'middle',
        position: 'relative',
        top: -1
      });

      var isDisabled = this.props.disabled !== undefined && !!this.props.disabled;
      var showSuffix = text && allowClear && !isDisabled;
      var suffix = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Icon, {
        key: "clear",
        className: "lov-clear",
        type: "close-circle",
        onClick: this.emitEmpty
      }), this.searchButton());
      var lovClassNames = [className, 'lov-input'];

      if (showSuffix) {
        lovClassNames.push('lov-suffix');
      }

      if (isDisabled) {
        lovClassNames.push('lov-disabled');
      }

      var _this$state2 = this.state,
          _this$state2$title = _this$state2.title,
          title = _this$state2$title === void 0 ? '' : _this$state2$title,
          _this$state2$lov = _this$state2.lov,
          lov = _this$state2$lov === void 0 ? {} : _this$state2$lov,
          modalVisible = _this$state2.modalVisible,
          loading = _this$state2.loading,
          lovModalKey = _this$state2.lovModalKey;
      var modalProps = {
        title: title,
        width: viewOnly ? 680 : 1325,
        destroyOnClose: true,
        wrapClassName: 'lov-modal',
        maskClosable: false,
        onOk: this.selectAndClose,
        okButtonProps: {
          loading: saveLoading
        },
        bodyStyle: title ? {
          padding: '16px 32px 0'
        } : {
          padding: '56px 32px 0'
        },
        onCancel: this.onCancel,
        style: {
          minWidth: 400
        },
        visible: modalVisible
      };
      var _this$props9 = this.props,
          disabled = _this$props9.disabled,
          onChange = _this$props9.onChange;
      var inputProps = {
        disabled: disabled,
        onChange: onChange // onClick,

      };
      return /*#__PURE__*/React.createElement(React.Fragment, null, viewOnly ? /*#__PURE__*/React.createElement("a", {
        onClick: this.onSearchBtnClick
      }, intl.get('cpaas.common.button.view').d('查看'), values.length > 0 ? /*#__PURE__*/React.createElement(Tag, {
        color: "#108ee9",
        style: {
          height: 'auto',
          lineHeight: '15px',
          marginLeft: '4px'
        }
      }, values.length) : null) : /*#__PURE__*/React.createElement(Input, Object.assign({
        readOnly: true,
        value: text,
        style: inputStyle // Lov 组件垂直居中样式，作用于 ant-input-group-wrapper
        ,
        suffix: suffix
      }, _omit(inputProps, omitProps), {
        className: lovClassNames.join(' ')
      })), /*#__PURE__*/React.createElement(Modal, modalProps, viewOnly ? /*#__PURE__*/React.createElement(ViewOnlyModal, {
        lov: lov,
        currentValue: value,
        ldpData: ldpData,
        queryParams: queryParams,
        queryInputProps: queryInputProps,
        lovLoadLoading: loading,
        wrappedComponentRef: this.modalRef,
        isDbc2Sbc: isDbc2Sbc,
        code: code
      }) : /*#__PURE__*/React.createElement(TransferModal, {
        key: lovModalKey,
        lov: lov,
        currentValue: value,
        ldpData: ldpData,
        queryParams: queryParams,
        queryInputProps: queryInputProps,
        lovLoadLoading: loading,
        wrappedComponentRef: this.modalRef,
        isDbc2Sbc: isDbc2Sbc,
        code: code
      })));
    }
  }]);

  return TransferLov;
}(React.Component), _class2.displayName = 'LovMulti', _class2), (_applyDecoratedDescriptor(_class.prototype, "initDisplayData", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "initDisplayData"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "selectAndClose", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "selectAndClose"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onCancel", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "onCancel"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onSearchBtnClick", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "onSearchBtnClick"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "emitEmpty", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "emitEmpty"), _class.prototype)), _class));
export { TransferLov as default };